import dotenv from "dotenv";
// 加载 .env 文件（默认 .env，也可以指定 .env.development）
dotenv.config({ path: ".env.development" });

import { join } from "path";
import { app, BrowserWindow, ipcMain, dialog } from "electron";
import axios from "axios";

const isDev = process.env.npm_lifecycle_event === "app:dev" ? true : false;

async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    title: "Open File",
  });
  if (!canceled) {
    return filePaths[0];
  }
}

let mainWindow: any;
function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1920,
    height: 1080,

    minimizable: true, //取消Windows自带的关闭最小化
    maximizable: false,
    autoHideMenuBar: true,
    icon: "../../assets/logo.ico",
    resizable: false, //禁止改变主窗口尺寸
    movable: false, //是否移动
    webPreferences: {
      preload: join(__dirname, "../preload/preload.js"),
    },
    // fullscreen: true, //设置全屏
  });

  // and load the index.html of the app.
  if (isDev) {
    mainWindow.loadURL("http://localhost:3000"); // Open the DevTools.
    // mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(join(__dirname, "../../index.html"));
    // mainWindow.webContents.openDevTools();
  }

  mainWindow.on("close", function (e: any) {
    // 阻止默认关闭行为
    e.preventDefault();
    showFormWindow();
    // let response = dialog.showMessageBoxSync(mainWindow, {
    //     type: 'question',
    //     buttons: ['Yes', 'No'],
    //     title: '退出',
    //     message: '确定退出?'
    // });
    // e.preventDefault()
    // //点击按钮 是
    // if(response == 0) {
    //     axios.post('http://localhost:5100/DMS/KSKH/Exit').then((res: any) => {
    //         if(res.data.code == 200){
    //             app.exit()
    //         }else{
    //             e.preventDefault()
    //         }
    //     })
    // }
  });
  mainWindow.on("closed", () => {
    mainWindow = null;
  });
  // mainWindow.loadURL( //this doesn't work on macOS in build and preview mode
  //     isDev ?
  //     'http://localhost:3000' :
  //     join(__dirname, '../../index.html')
  // );
}

let formWindow: BrowserWindow | null = null;
function showFormWindow() {
  if (formWindow) return;

  formWindow = new BrowserWindow({
    width: 400,
    height: 270,
    modal: true,
    frame: false,
    parent: mainWindow!,
    resizable: false,
    minimizable: false, //取消Windows自带的关闭最小化
    maximizable: false,
    autoHideMenuBar: true,
    movable: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  formWindow.setMenu(null);
  // 根据不同环境 加载不同的HTML路径 dialog.html放到了public 打包之后会在dist目录下
  if (!isDev) {
    // 生产环境：从打包后的资源目录加载dist/electron/main.js
    formWindow.loadFile(join(__dirname, "../../dialog/index.html"));
  } else {
    // 开发环境：从当前主应用src/electron/main.ts中使用相对路径加载
    formWindow.loadFile(join(__dirname, "../../../public/dialog/index.html"));
  }
  formWindow.on("closed", () => {
    formWindow = null;
  });
}

// 监听关闭对话框事件
ipcMain.on("close-dialog", () => {
  formWindow?.close();
});

ipcMain.on("form-submitted", (event, data) => {
  // const port = getURL();
  const baseURL = isDev
    ? process.env.VITE_BASE_URL
    : `http://localhost:5100/`;
    
  //先验证用户成功再调用退出Exit
  event.preventDefault();
  axios.post(`${baseURL}DMS/KSKH/Login`, data).then((res: any) => {
    if (res.data.code == 200) {
      if (formWindow) {
        formWindow.close();
        //调用Exit 关闭App
        axios.post(`${baseURL}DMS/KSKH/Exit`).then((res: any) => {
          if (res.data.code == 200) {
            app.exit();
          } else {
            event.preventDefault();
            showAlert(res.data.msg);
          }
        });
        // if (mainWindow) {
        //   mainWindow.destroy(); // 直接销毁主窗口，不再触发close事件
        //   // 或者使用 mainWindow.close() ，如果需要再次触发关闭流程
        // }
      }
    } else {
      event.preventDefault();
      showAlert(res.data.msg);
    }
  });
});

function showAlert(message: string) {
  dialog.showMessageBox({
    title: "提示",
    message: message,
    type: "info", // 可设为 'info'、'error'、'warning' 等
    buttons: ["确定"], // 只显示一个确认按钮
  });
}

//获取API URL
function getURL() {
  const baseURL = process.env.VITE_BASE_URL as string;
  const fullUrl = new URL(baseURL);
  const port = fullUrl.port;
  return port;
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  ipcMain.handle("dialog:openFile", handleFileOpen);
  createWindow();
  app.on("activate", function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
}
